package Divers;

import general.Fichiers;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.sun.xml.internal.ws.api.addressing.WSEndpointReference.Metadata;
import utilitaire.UtilitaireFichier;

public class MiseEnForme
{
	// ***** ENTREE *****//
	private static final String dossierAParcourir = //"H:\\Images";

	"D:\\mes images";
	// "D:\\mes images\\test";
	// "H:\\Images\\Copains voisins";
	public static void main(String[] args)
	{
		System.out.println("Debut de programme");
		try {
			File source = new File(dossierAParcourir + "\\");
			analyseDossier(source);
		}
		catch (Exception e) {
			System.out.println("ERREUR : " + e.getMessage() + ", "
					+ e.toString());
		}
		System.out.println("Fin de programme");
	}

	public static boolean analyseDossier(File path) throws Exception
	{
		try {
			boolean dossierContientSousDossier = false;
			if (path.exists()) {
				File[] files = path.listFiles();
				for (int i = 0; i < files.length; i++) {
					if (files[i].isDirectory()) {
						dossierContientSousDossier = true;
						analyseDossier(files[i]);
						// remplace - par _
						if (files[i].getName().contains("-")) {
							String newName = files[i].getName().replace("-",
									"_");
							newName = files[i].getParent() + File.separator
									+ newName;
							rename(files[i], newName);
						}
						// Mettre Majuscule sur le premier mot
						String nomFile = files[i].getName();
						String[] nomFileSplit = files[i].getName().split("_");
						boolean replaceMaj = false;
						for (int j = 0; j < nomFileSplit.length; j++) {
							String split = nomFileSplit[j];
							if (!beginByMaj(split) && !replaceMaj) {
								replaceMaj = true;
								nomFile = nomFile.replace(split,
										majFirstChar(split));
							}
						}
						if (replaceMaj) {
							rename(files[i], nomFile);
						}
					}
				}
				if ((!dossierContientSousDossier && !path.getName().startsWith(
						"20"))
						|| path.getName().contains("__")) {
					String newName = path.getName();
					Date date = getTakenDate(path);
					SimpleDateFormat formatDateJour = new SimpleDateFormat(
							"yyyy_MM_dd");
					String dateFormatee = "";
					if (date != null) {
						dateFormatee = formatDateJour.format(date);
						newName = dateFormatee + "__" + newName;
						newName = path.getParent() + File.separator + newName;
						if (!dateFormatee.equals("2013_06_10")) {
							rename(path, newName);
						}
					}
				}
			}
		}
		catch (Exception e) {
			throw e;
		}
		return true;
	}

	private static void rename(File file, String newName)
	{
		long lastModif = file.lastModified();
		System.out.println("Rename : " + file.getName() + " : "
				+ file.renameTo(new File(newName)));
		file.setLastModified(lastModif);
	}

	private static boolean beginByMaj(String value)
	{
		if (value != null && !value.isEmpty()) {
			String firstChar = value.substring(0, 1);
			return firstChar.equals(firstChar.toUpperCase());
		}
		else {
			return true;
		}
	}

	private static String majFirstChar(String value)
	{
		if (value != null && !value.isEmpty()) {
			String fisrtChar = value.substring(0, 1);
			return fisrtChar.toUpperCase() + value.substring(1);
		}
		else {
			return value;
		}
	}

	private static Date getTakenDate(File repertoire) throws IOException, InterruptedException
	{
		Date dateTaken = null;
		File firstFile = null;
		if (repertoire.listFiles().length != 0) {
			firstFile = repertoire.listFiles()[0];
		}
//		ExifToolExtractor exifToolExtractor = new ExifToolExtractor(null);
//				//"C:\\exiftool(-k).exe");
//		ExifInfo exifInfo = exifToolExtractor.getExifInfo(firstFile.getPath());
//		System.out.println(exifInfo);
//		
		Metadata metadata = null;
        try {
            metadata = JpegMetadataReader.readMetadata(firstFile.getPath());
        } catch (JpegProcessingException ex) {
            ex.printStackTrace();
        }
        // iterate through metadata directories
        Iterator directories = metadata.getDirectoryIterator();
        if(directories != null) {
            while (directories.hasNext()) {
                Directory directory = (Directory)directories.next();
                // iterate through tags and print to System.out
                Iterator tags = directory.getTagIterator();
                while (tags.hasNext()) {
                    Tag tag = (Tag)tags.next();
                    // use Tag.toString()
                    System.out.println(tag);
                }
            }
        }
		
		ImageInputStream iis = ImageIO.createImageInputStream(firstFile);
		Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
		if (readers != null && readers.hasNext()) {
			// pick the first available ImageReader
			ImageReader reader = readers.next();
			// attach source to the reader
			reader.setInput(iis, true);
			// read metadata of first image
			IIOMetadata metadata = reader.getImageMetadata(0);
			String[] names = metadata.getMetadataFormatNames();
			int length = names.length;
			for (int i = 0; i < length; i++) {
				System.out.println("Format name: " + names[i]);
				displayMetadata(metadata.getAsTree(names[i]));
			}
		}
		return dateTaken;
	}

	private static void displayMetadata(Node root)
	{
		displayMetadata(root, 0);
	}

	private static void indent(int level)
	{
		for (int i = 0; i < level; i++)
			System.out.print("    ");
	}

	private static void displayMetadata(Node node, int level)
	{
		indent(level);
		System.out.print("<" + node.getNodeName());
		NamedNodeMap map = node.getAttributes();
		if (map != null) {
			int length = map.getLength();
			for (int i = 0; i < length; i++) {
				Node attr = map.item(i);
				System.out.print(" " + attr.getNodeName() + "=\""
						+ attr.getNodeValue() + "\"");
			}
		}
		Node child = node.getFirstChild();
		if (child == null) {
			System.out.println("/>");
			return;
		}
		System.out.println(">");
		while (child != null) {
			displayMetadata(child, level + 1);
			child = child.getNextSibling();
		}
		indent(level);
		System.out.println("</" + node.getNodeName() + ">");
	}
}
